const garbage_data = require('./garbage-sort/garbage-sort-data.js');
const garbage_categroy = require('./garbage-sort/garbage-categroy.js');

function search(text, successCallback) {

  var data = garbage_data.garbage_sort_data;

  var searchResult = [];
  data.forEach(function (categroyItem) {
    if (categroyItem && categroyItem.data && categroyItem.data.length > 0) {
      categroyItem.data.forEach(function (letterItem) {
        var garbageItem = letterItem.garbageItem;
        garbageItem.forEach(function (item) {
          if (text.indexOf(item) > -1 || item.indexOf(text) > -1) {//模糊搜索
            searchResult.push({
              "categroyName": garbage_categroy.getCategoryName(categroyItem.categroy - 1),
              "garbageName": item,
              "categroyId": categroyItem.categroy
            })
          }
        })
      })
    }
  })
  if (searchResult.length) {//本地结果返回    
    successCallback(searchResult);
  } else {//API结果返回
    wx.request({
      url: 'https://api.tianapi.com/txapi/lajifenlei/index?key=' + APIKEY + '&word=' + text,
      success: function (res) {
        if (res.data.code == 200) {
          var rawRes = res.data.newslist
          successCallback(parseRes(rawRes, searchResult))
        } else {
          console.log(res.data.msg)
          successCallback(searchResult)
        }
      },
      fail: function (err) {
        console.log(err)
      }
    })
  }
}

function parseRes(rawRes, searchResult) {
  rawRes.forEach(element => {
    searchResult.push({
      "categroyName": garbage_categroy.getCategoryName(element.type),
      "garbageName": element.name,
      "categroyId": element.type + 1
    })
  });
  return searchResult
}

var APIKEY = "1d574ffc1e47fa65274294e074b361f1";

module.exports = {
  search: search,
}